package com.xuerhua.yxt.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.xuerhua.yxt.common.AppUser;
import com.xuerhua.yxt.common.RspResult;
import com.xuerhua.yxt.common.enums.Status;
import com.xuerhua.yxt.common.enums.StudentSignUpType;
import com.xuerhua.yxt.model.StudentSchoolAge;
import com.xuerhua.yxt.model.StudentSignUp;
import com.xuerhua.yxt.model.StudentSignupUser;
import com.xuerhua.yxt.model.TeacherSignUp;
import com.xuerhua.yxt.service.IStudentSchoolAgeService;
import com.xuerhua.yxt.service.IStudentSignUpService;
import com.xuerhua.yxt.service.ITeacherSignUpService;
import com.xuerhua.yxt.utils.StringUtil;
import net.minidev.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


@RequestMapping("signup")
@Controller
public class SignupController extends BaseController
{
  private Logger logger = LoggerFactory.getLogger(SignupController.class);
  @Autowired
  private IStudentSchoolAgeService studentSchoolAgeService;
  @Autowired
  private IStudentSignUpService studentSignUpService;

  @Autowired
  private ITeacherSignUpService teacherSignUpService;

  @RequestMapping("newStudent")
  public String newStuSignUp(Model model)
  {
    model.addAttribute("signUpType", StudentSignUpType.NEW_STUDENT.getCode());
    StudentSignupUser user = (StudentSignupUser)this.session.getAttribute("studentSignup");
    if (user != null) {
      String type = this.request.getParameter("type");
      if ((StringUtils.isNotBlank(type)) && ("sign".equals(type))) {
        model.addAttribute("user", user);
        return "signUp/newStu";
      }
      List list = this.studentSignUpService.selectListByUserId(StudentSignUpType.NEW_STUDENT.getCode(), user.getId());
      if (!StringUtil.isNullOrEmpty(list)) {
        model.addAttribute("list", list);
        return "signUp/myStudentList";
      }
      model.addAttribute("user", user);
      return "signUp/newStu";
    }
    return "signUp/studentLogin";
  }

  @RequestMapping("middleStudent")
  public String middleStuSignUp(Model model)
  {
    model.addAttribute("signUpType", StudentSignUpType.MIDDLE_STUDENT.getCode());
    StudentSignupUser user = (StudentSignupUser)this.session.getAttribute("studentSignup");
    if (user != null) {
      String type = this.request.getParameter("type");
      if ((StringUtils.isNotBlank(type)) && ("sign".equals(type))) {
        model.addAttribute("user", user);
        return "signUp/middleStu";
      }
      List list = this.studentSignUpService.selectListByUserId(StudentSignUpType.MIDDLE_STUDENT.getCode(), user.getId());
      if (!StringUtil.isNullOrEmpty(list)) {
        model.addAttribute("list", list);
        return "signUp/myStudentList";
      }
      model.addAttribute("user", user);
      return "signUp/middleStu";
    }
    return "signUp/studentLogin";
  }

  @RequestMapping("internatStudent")
  public String internatStuSignUp(Model model)
  {
    model.addAttribute("signUpType", StudentSignUpType.INTERNAT_STUDENT.getCode());
    StudentSignupUser user = (StudentSignupUser)this.session.getAttribute("studentSignup");
    if (user != null) {
      String type = this.request.getParameter("type");
      if ((StringUtils.isNotBlank(type)) && ("sign".equals(type))) {
        model.addAttribute("user", user);
        return "signUp/internatStu";
      }
      List list = this.studentSignUpService.selectListByUserId(StudentSignUpType.INTERNAT_STUDENT.getCode(), user.getId());
      if (!StringUtil.isNullOrEmpty(list)) {
        model.addAttribute("list", list);
        return "signUp/myStudentList";
      }
      model.addAttribute("user", user);
      return "signUp/internatStu";
    }
    return "signUp/studentLogin";
  }

  @RequestMapping({"studentLogin"})
  public String studentLogin() {
    return "signUp/studentLogin";
  }

  @RequestMapping({"studentReg"})
  public String studentReg() {
    return "signUp/studentReg";
  }

  @RequestMapping({"teacher"})
  public String teacherSignUp(Model model) {
    return "signUp/teacher";
  }

  @RequestMapping({"student/admin"})
  @ResponseBody
  Object studentAdmin(StudentSignupUser record)
  {
    try
    {
      StudentSignupUser user = this.studentSignUpService.selectUserForAdmin(
        record.getUserAccount(), record.getUserPassword());
      if (user == null) {
        return new RspResult(Status.PWD_ERROR);
      }
      user.setUserPassword(null);
      this.session.setAttribute("studentSignup", user);
      return new RspResult(Status.SUCCESS);
    } catch (Exception e) {
      this.logger.error("---studentAdmin error={}", e);
    }
    return new RspResult(Status.FAIL);
  }

  @RequestMapping({"student/reg"})
  @ResponseBody
  Object studentReg(StudentSignupUser user)
  {
    try
    {
      this.studentSignUpService.addStudentUser(user);
      user.setUserPassword(null);
      this.session.setAttribute("studentSignup", user);
      return new RspResult(Status.SUCCESS);
    } catch (Exception e) {
      this.logger.error("---studentAdmin error={}", e);
    }
    return new RspResult(Status.FAIL);
  }

  @RequestMapping({"student/middleStudentGrade"})
  @ResponseBody
  Object middleStudentGrade() {
    //FIXME 这个等我做到这部分再改，暂时不知道怎么传schoolId过去 - hhk
    AppUser appUser = getAppUser();
    return this.studentSignUpService.selectMiddleStudentGrade(appUser.getTeacher().getSchoolId());
  }

  @RequestMapping({"student/submit"})
  @ResponseBody
  Object signUpStudentSubmit(StudentSignUp record)
  {
    try
    {
      StudentSignupUser user = (StudentSignupUser)this.session.getAttribute("studentSignup");
      record.setUserPhone(user.getUserAccount());
      record.setUserId(user.getId());
      this.studentSignUpService.addAndUpdate(record);
      return new RspResult(Status.SUCCESS, record.getId());
    } catch (Exception e) {
      this.logger.error("---signUpSubmit error={}", e);
    }
    return new RspResult(Status.FAIL);
  }
  @RequestMapping({"teacher/submit"})
  @ResponseBody
  Object signUpTeacherSubmit(TeacherSignUp record) {
    try { this.teacherSignUpService.addAndUpdate(record);
      return new RspResult(Status.SUCCESS, record.getId());
    } catch (Exception e) {
      this.logger.error("---signUpSubmit error={}", e);
    }
    return new RspResult(Status.FAIL);
  }

  /**
   * 一年级新生报名
   * @param studentSignUp
   * @return
   */
  @RequestMapping({"student/addNewborn"})
  @ResponseBody
  public Object addNewborn(StudentSignUp studentSignUp) {
    //把getStudentBirthday里面的所有标点符号换掉，剩下数字
    int sigup = Integer.valueOf(studentSignUp.getStudentBirthday().replaceAll("\\p{Punct}",""));  // \\p{Punct}：正则表达式，代表标点符号
    Integer grade = 1;
    StudentSchoolAge age = studentSchoolAgeService.selectAge(grade);
    int mi = Integer.valueOf(age.getSchoolAgeMinimum().replaceAll("\\p{Punct}",""));
    //判断年龄是否符合要求
    if(sigup <= mi) {
      try {
	      StudentSignupUser user = (StudentSignupUser)this.session.getAttribute("studentSignup");
	      studentSignUp.setUserPhone(user.getUserAccount());
	      studentSignUp.setUserId(user.getId());
	      this.studentSignUpService.addAndUpdateNewStudent(studentSignUp);
	      return new RspResult(Status.SUCCESS, studentSignUp.getId());
      } catch (Exception e) {
        this.logger.error("---student/addNewborn error={}", e);
      }
	}
    return new RspResult(Status.PARAM_FAIL.getCode(), "年龄低于入学年龄，不能报名");
  }

  /**
   * 一年级新生详情
   * @param id
   * @return
   */
  @RequestMapping("newStudent/detail/{id}")
  public ModelAndView newStudentDetail(@PathVariable Integer id) {
    StudentSignUp singn = studentSignUpService.selectByPrimaryKey(id);
    ModelAndView mo = new ModelAndView();
    mo.setViewName("signUp/newStuDetail");
    mo.addObject("singn", singn);
    return mo;
  }
  
  /**
   * 插班生详情
   * @param id
   * @return
   */
  @RequestMapping("middleStudent/detail/{id}")
  public ModelAndView middleStudent(@PathVariable Integer id) {
    StudentSignUp singn = studentSignUpService.selectByPrimaryKey(id);
    ModelAndView mo = new ModelAndView();
    mo.setViewName("signUp/middleStudentDetail");
    mo.addObject("singn", singn);
    return mo;
  }
}